// 对象池：实现对象池化以重用元素，减少创建销毁开销
import { fabric } from 'fabric';

class ObjectPool {
    constructor(createFunc, options = {}) {
        this.createFunc = createFunc;
        this.pool = [];
        this.minSize = options.minSize || 10; // 最小池大小
        this.maxSize = options.maxSize || 100; // 默认最大池大小
        this.targetSize = options.maxSize || 50; // 目标池大小
        this.stats = {
            created: 0,
            reused: 0,
            released: 0,
            invalid: 0,
            lastAdjustTime: Date.now()
        };
        this.adjustInterval = options.adjustInterval || 60000; // 调整间隔(ms)
    }

    acquire() {
        // 清理过期对象
        this.cleanPool();

        if (this.pool.length > 0) {
            this.stats.reused++;
            const reusedObj = this.pool.pop();
            if (this.isValid(reusedObj)) {
                if (reusedObj._fabric) {
                    reusedObj._reused = true;
                }
                return reusedObj;
            } else {
                this.stats.invalid++;
            }
        }

        this.stats.created++;
        const newObj = this.createFunc();
        if (newObj._fabric) {
            newObj._poolCreated = true;
        }
        return newObj;
    }

    release(obj) {
        if (!obj || !this.isValid(obj)) {
            this.stats.invalid++;
            return;
        }

        // 自动调整池大小
        this.autoAdjustSize();

        if (this.pool.length >= this.maxSize) {
            return;
        }

        this.stats.released++;
        this.resetObject(obj);
        this.pool.push(obj);
    }

    resetObject(obj) {
        if (obj instanceof fabric.Object) {
            // 最小化重置操作
            obj.set({
                visible: false,
                left: 0,
                top: 0
            });
            obj.setCoords();
        }
    }

    isValid(obj) {
        if (!obj) return false;
        // 检查对象是否有效
        if (obj instanceof fabric.Object) {
            return !obj.isDestroyed && obj.canvas === null;
        }
        return true;
    }

    cleanPool() {
        this.pool = this.pool.filter((obj) => this.isValid(obj));
    }

    autoAdjustSize() {
        const now = Date.now();
        if (now - this.stats.lastAdjustTime < this.adjustInterval) return;

        this.stats.lastAdjustTime = now;
        const reuseRate = this.getStats().reuseRate;

        // 根据重用率动态调整池大小
        if (reuseRate > 0.7) {
            this.targetSize = Math.min(this.maxSize, Math.max(this.minSize, this.targetSize + 5));
        } else if (reuseRate < 0.3) {
            this.targetSize = Math.max(this.minSize, this.targetSize - 5);
        }

        // 调整池大小
        while (this.pool.length > this.targetSize) {
            this.pool.pop();
        }
    }

    getStats() {
        const total = this.stats.reused + this.stats.created;
        return {
            ...this.stats,
            poolSize: this.pool.length,
            targetSize: this.targetSize,
            reuseRate: total > 0 ? this.stats.reused / total : 0,
            invalidRate: total > 0 ? this.stats.invalid / total : 0
        };
    }
}

export default ObjectPool;
